<template>
  <div style="height: 100%">

      <div v-if="is_show_noDish" style="width: 100%;height: 100%;display: flex;align-items: center;justify-content: center">
          <div style="width: 50%;height: 50%;position: relative;left: 200px"><img src="/imgs/nodata/nodata.svg" /></div>
      </div>
      <el-row :gutter="10" style="margin-left: 12px" type="flex">
          <el-col :span="4" v-for="(item,index) in dish_arr" style="margin-top: 10px">
              <el-card>
                  <el-avatar shape="square" style="margin-left: 10px;vertical-align: middle" :size=125 :src="BASE_URL+item.imgUrl" />
                  <p style="margin-left: 10px"><span style="color: #0aa1ed;">{{item.name}}</span></p>
                  <p style="color: #333;margin-left: 10px">价格：<span style="color: #42b983;">￥{{parseFloat(item.price).toFixed(2)}}/份</span></p>
                <el-collapse accordion>
                    <el-collapse-item title="介绍：" size="18px" style="color: #333;margin-left: 10px;font-weight: bold;" >
                      <p style="color: #333;margin-left: 10px; max-width: 100px; word-wrap: break-word;"
                      ><span style="color: #666;">{{item.description}}</span></p>
                    </el-collapse-item>
                </el-collapse>
                  <span style="color: #333;margin-left: 10px">加入购物车：</span>
                  <el-icon style="vertical-align: middle;margin-left: 10px;cursor:pointer;color: #42b983;font-weight: bolder" @click="open_dialog(item.id)"><ShoppingCart /></el-icon>
              </el-card>
          </el-col>
      </el-row>
      <el-dialog v-model="dialog_choose_dish" :before-close="close_dialog" title="请选择数量" style="width: 300px;">
          <el-form>
              <el-form-item>
                  <el-icon style="vertical-align: middle;margin-right: 10px;cursor: pointer" @click="decrease"><Remove /></el-icon>
                  <span>{{choose_dish_form.number}}</span>
                  <el-icon style="vertical-align: middle;margin-left: 10px;cursor:pointer;" @click="increase"><CirclePlusFilled /></el-icon>
              </el-form-item>
              <el-button @click="close_dialog">取消</el-button>
              <el-button @click="addDishToCart">确认</el-button>
          </el-form>
      </el-dialog>
  </div>

</template>

<script setup>

import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import {computed, inject, onMounted, ref, watch} from "vue";
import {useRoute} from "vue-router";
import store from "@/store";
import qs from "qs";
import router from "@/router";


//一进页面查询是否已选择餐桌
const search_is_choose_table = ()=>{
    let search_condition = {}
    search_condition.userId=user.value.id
    search_condition.branchId=store.state.global_branch_Id
    search_condition.diningStatus='1'//status未付款0，已付款1，。。Dining status已选餐桌/就坐1 离开2（订单结束）
    let data = qs.stringify(search_condition)
    axios.get(BASE_URL+'/v1/orders/selectByCondition?'+data)
        .then((response)=>{
            if(response.data.code===2000){
                if(response.data.data.length===0){
                    //未选餐桌
                    //用户从餐厅1选了餐桌，此时从首页进入餐厅2，由于设置了sessionStorage，store.state.global_my_table_info还存储了餐厅1的餐桌信息，
                    //因此需要更新store.state.global_my_table_info的值
                    store.state.global_my_table_info={id:0,name:''}
                    ElMessageBox.confirm(
                        '未选餐桌不能点餐，是否去餐桌页面选餐桌',
                        '提示',
                        {
                            confirmButtonText: '确认',
                            cancelButtonText: '继续浏览',
                            type: 'warning',
                        }
                    ).then(() => {
                        router.push('/myTable')
                    }).catch(() => {
                        ElMessage({
                            type: 'info', message: '已取消',
                        })
                    })
                }else{
                    //已选定餐桌
                    let tableId = response.data.data[0].tableId
                    //获取当前订单id
                    store.state.global_current_orderId=response.data.data[0].id
                    axios.get(BASE_URL+'/v1/tables/select?id='+tableId)
                        .then((response)=>{
                            if(response.data.code===2000){
                                store.state.global_my_table_info.id=response.data.data[0].tableId
                                store.state.global_my_table_info.name=response.data.data[0].name
                            }else{
                                ElMessage.error(response.data.msg)
                            }
                        })
                }
            }else{
                ElMessage.error(response.data.msg)
            }
        })
}
onMounted(()=>{
    setTimeout(function (){
        if(store.state.global_type_arr.length!==0){
          search_is_choose_table()
        }
    },10)
    //具体来说，当一个父组件包含了子组件时，Vue 的挂载过程会先完成父组件的模板解析，
    // 并在这个过程中遇到子组件时立即开始子组件的创建和挂载。
    // 因此，子组件的 onMounted 钩子通常会在父组件的 onMounted 钩子之前被调用。

    //需要注意的是，这个顺序假设了没有异步操作阻塞了组件的挂载过程。如果有异步操作或使用了 nextTick、setTimeout 等方法来延迟某些操作，则实际的执行顺序可能会有所不同。
})

//用户
const user = ref(getUser())
//菜品数组
const dish_arr = computed(() => store.state.dish_arr)


//选菜对话框
const dialog_choose_dish = ref(false)
//选菜提交表单
const choose_dish_form = ref({userId:'',dishId:'',number:1,branchId:''})
//打开对话框表单
const open_dialog = (dishId)=>{
    if(store.state.global_my_table_info.id===0){
        ElMessageBox.confirm(
            '未选餐桌不能点餐，是否去餐桌页面选餐桌',
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '继续浏览',
                type: 'warning',
            }
        ).then(() => {
            router.push('/myTable')
        }).catch(() => {
            ElMessage({
                type: 'info', message: '已取消',
            })
        })
    }else{
        choose_dish_form.value.dishId=dishId
        dialog_choose_dish.value=true
    }

}
//增加数量
const increase = ()=>{
    choose_dish_form.value.number+=1
}
//减少数量
const decrease = ()=>{
    if(choose_dish_form.value.number===1){
        choose_dish_form.value.number=1
    }else{
        choose_dish_form.value.number-=1
    }
}
//添加到购物车
const addDishToCart = ()=>{
    choose_dish_form.value.userId=user.value.id
    choose_dish_form.value.branchId=store.state.global_branch_Id
    let data = qs.stringify(choose_dish_form.value)
    axios.post(BASE_URL+'/v1/cart/insert',data)
        .then((response)=>{
            if(response.data.code===2000){
                ElMessage.success('加入成功')
                dialog_choose_dish.value=false
                choose_dish_form.value={userId:'',dishId:'',number:1,branchId:''}
                select_cart()

            }else{
                ElMessage.error(response.data.msg)
            }
        })

}
//查询购物车记录
const select_cart = ()=>{
    let branchId = store.state.global_branch_Id
    let userId = user.value.id
    axios.get(BASE_URL+'/v1/cart/select?branchId='+branchId+'&userId='+userId)
        .then((response)=>{
            if(response.data.code===2000){
                store.state.global_shopping_cart_arr=response.data.data
            }else{
                ElMessage.error(response.data.msg)
            }
        })
}
//关闭对话框表单
const close_dialog = ()=>{
    if(confirm('确认关闭吗')){
        dialog_choose_dish.value=false
        choose_dish_form.value={userId:'',dishId:'',number:1,branchId:''}
    }
}


//根据菜名和分店id查询菜品
const select_dish_by_name_branchId = ()=>{
    let branchId = store.state.global_branch_Id//分店id
    let name = store.state.search_global//菜名
    axios.get(BASE_URL+'/v1/dish/select?branchId='+branchId+'&name='+name)
        .then((response)=>{
            if(response.data.code===2000){
                store.state.dish_arr=response.data.data
            }else{
                ElMessage.error(response.data.msg)
            }
        })
}
//监听全局搜索框的值的变化
watch(() =>store.state.search_i,(newValue,oldValue)=> {

    select_dish_by_name_branchId()
},{ immediate: false })
watch(() =>store.state.dish_arr,(newValue,oldValue)=> {
    if(newValue.length===0){
        is_show_noDish.value=true
    }else{
        is_show_noDish.value=false
    }

},{ immediate: false })
const is_show_noDish = ref(false)
</script>

<style scoped>

</style>